import os
from datetime import datetime

from django.shortcuts import render,render_to_response
from django.template import RequestContext
from django.http import HttpResponse

from scripts.plots import plt_availability
from scripts.utils import AttrDict

from apps.data.models import DataType
from apps.stations.models import Station
from apps.instruments.models import InstrumentType, Instrument



def add_attr(iterable, var, value):
    for obj in iterable:
        if isinstance(obj, dict):
            obj[var]=value
        else:
            setattr(obj, var, value)        

def availability(request, datatype=None):
    args = {}
    dt1 = request.GET.get('dt1', datetime.now().strftime('%Y/%m/%d'))
    dt2 = request.GET.get('dt2', datetime.now().strftime('%Y/%m/%d'))
    network = AttrDict(value=request.GET.get('network', None), check='checked', collapse='')
    country = AttrDict(value=request.GET.get('country', None), check='checked', collapse='')
    station = AttrDict(value=request.GET.get('station', None), check='checked', collapse='')

    if datatype:
        url_plot = '/django/miscellaneous/availability/plot.png?'   
        #url_plot = '/download?plot=yes'
        dtype = DataType.objects.get(alias=datatype)
        url_plot += 'dtype=%s' % dtype.alias
        args['data_type'] = dtype
        args['networks'] = Instrument.objects.filter(data__datatype_id=dtype.pk).distinct().order_by('network').values('network')
        add_attr(args['networks'], 'check', 'checked')
        sites = Station.objects.filter(instrument__data__datatype_id=dtype.pk)
        
        if 'dt1' in request.GET:            
            url_plot += '&dt1=%s' % dt1
        if 'dt2' in request.GET:
            url_plot += '&dt2=%s' % dt2
        if network.value=='all':
            network.collapse = 'in'
        elif network.value:
            networks = [nn.lower() for nn in network.value.split(',') if nn]
            sites = sites.filter(instrument__network__in=networks).distinct()
            url_plot += '&network=%s' % network.value
            network.check = ''
            network.collapse = 'in'
            for nn in args['networks']:
                if nn['network'].lower() not in networks:
                    nn['check'] = ''
        
        args['network'] = network
        args['countries'] = sites.order_by('country').values('country').distinct()
        add_attr(args['countries'], 'check', 'checked')
        if country.value=='all':
            country.collapse = 'in'
        elif country.value:
            countries = [cc.lower() for cc in country.value.split(',') if cc]
            sites = sites.filter(country__in=countries).distinct()
            url_plot += '&country=%s' % country.value
            country.check = ''
            country.collapse = 'in'
            for cc in args['countries']:
                if cc['country'].lower() not in countries:
                    cc['check'] = ''
        
        args['country'] = country
        args['stations'] = sites.order_by('name').values('name', 'instrument__code')
        add_attr(args['stations'], 'check', 'checked')
        if station.value=='all':
            station.collapse = 'in'
        elif station.value:
            stations = [ss.lower() for ss in station.value.split(',') if ss]
            url_plot += '&sites=%s' % station.value
            station.check = ''
            station.collapse = 'in'
            for ss in args['stations']:
                if ss['instrument__code'].lower() not in stations:
                    ss['check'] = ''
        
        args['station'] = station
        args['url_plot'] = url_plot
    
    dtypes = DataType.objects.order_by('-data__instrument__type', 'name').distinct()
    ndtypes = []
    instruments = []
    typeid = -100
    for dtype in dtypes:
        type_id = DataType.objects.filter(pk=dtype.id).distinct()
        if typeid<>type_id.values('data__instrument__type')[0]['data__instrument__type']:
            typeid = type_id.values('data__instrument__type')[0]['data__instrument__type']
            inst = type_id.values('data__instrument__type__name')[0]['data__instrument__type__name']
            ndtypes.append(inst)
            instruments.append(inst)
        ndtypes.append(dtype)
    args['data_types'] = ndtypes
    args['instruments'] = instruments
    args['dt1'] = dt1        
    args['dt2'] = dt2
    return render_to_response('availability.html', args, context_instance=RequestContext(request))

def plot_availability(request):
    dt1 = request.GET.get('dt1', datetime.now().strftime('%Y/%m/%d'))
    dt2 = request.GET.get('dt2', datetime.now().strftime('%Y/%m/%d'))
    dtype = request.GET.get('dtype', None)
    network = request.GET.get('network', None)
    country = request.GET.get('country', None)
    station = request.GET.get('station', None)
    img = plt_availability(dtype=dtype, dt1=dt1, dt2=dt2, network=network, country=country, station=station, output='web')
    response = HttpResponse(img, content_type='image/png')
    return response

def plot_test(request):
    import random
    import django
    import datetime
    os.environ['HOME'] = '/var/www/mpl'
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    ax.set_title(request.GET['datatype'])
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

def datasize(request):
    return render_to_response('datasize.html', {}, context_instance=RequestContext(request))
    
